﻿using System.Collections.Generic;
using System.Linq;
using ZilLion.Service.Core.DapperWrapper;
using ZilLion.Service.Core.DapperWrapper.SqlServer;
using ZilLion.Service.TaskPlatform.Domain.Entity;
using ZilLion.Service.TaskPlatform.Domain.Respository.Interface;

namespace ZilLion.Service.TaskPlatform.Domain.Respository.Sqlserver
{
    public class TaskCommandRespository : SqlServerRespository<TaskConmmandEntity>, ITaskCommandRespository
    {
        public TaskCommandRespository()
        {
            Context = new TaskRunnerSqlserverContext();
        }

        //public async Task<string> GetNewGuidAsync()
        //{
        //    return await Task.Run(() =>
        //    {
        //        Thread.Sleep(5000);
        //        return $@"{Guid.NewGuid():N}_HashCode:{GetHashCode()}";
        //    });
        //}
        public IEnumerable<TaskConmmandEntity> GetAllTaskConmmandEntities(string nodeid = null)
        {
            return nodeid.IsNotNullOrEmpty()
                ? GetList("select * from [task_command] where nodeid=@nodeid order by commandid asc", new {nodeid})
                : GetList("select * from [task_command] order by commandid asc ");
        }

        public TaskConmmandEntity GetTaskConmmandById(string conmmandId)
        {
            return GetList("select * from [task_command] where commandid=@conmmandId", new {conmmandId})
                .FirstOrDefault();
        }

        public IEnumerable<TaskConmmandEntity> GetUnHandleTaskConmmandEntitiesAsync(string nodeid)
        {
            return GetList(
                "select * from [task_command] where nodeid=@nodeid and commandstate=0  order by commandid asc",
                new {nodeid});
        }

        public void SaveTaskConmmandEntity(TaskConmmandEntity command, UnitOfWork unit = null)
        {
            var old = GetTaskConmmandById(command.CommandId ?? string.Empty);
            if (old == null)
                Add(command, unit);

            else
                Modify(command, unit);
        }
    }
}